﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevMed.Library;
using DevMed.Models;
using System.Web.Security;
using System.Web.Routing;

namespace DevMed.Controllers
{
    public class UsuarioController : Controller
    {
        //
        // GET: /Usuario/

        [Authorize]
        public ActionResult Index()
        {
 
            return View();
        }

        //
        // GET: /Usuario/MinhasEstatisticas

        public ActionResult MinhasEstatisticas()
        {
            MembershipUser U = Membership.GetUser(User.Identity.Name);
            //List<MinhasEstatisticasModels> lista = new List<MinhasEstatisticasModels>();
            //lista.Add(new MinhasEstatisticasModels());
            ViewBag.dataCriacao = U.CreationDate;
            return View();
        }

        //
        // GET: /Account/LogOff

        public ActionResult Logoff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }
        
        //
        // GET: /Usuario/Login

        
        public ActionResult Login()
        {
            if (Request.QueryString["ReturnUrl"] != null)
            {
                if (User.Identity.IsAuthenticated)
                {
                    TempData["erro"] = "Você não tem permissão para acessar esta área!";
                    return RedirectToAction("Index", "Usuario");
                }
                else
                {
                    TempData["erro"] = "Acesso restrito! Efetue o login!";
                    return RedirectToAction("Login", "Usuario");
                }
                
            }
            else if (User.Identity.IsAuthenticated)
            {
                TempData["erro"] = "Você já está logado no sistema!";
                return RedirectToAction("Index", "Usuario");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModels login)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(login.UserName, login.Password))
                {
                    FormsAuthentication.SetAuthCookie(login.UserName, login.RememberMe);
                    string[] roles = Roles.GetRolesForUser(login.UserName);

                    if (roles.Contains("Administrador"))
                    {
                       return RedirectToAction("Index", "Administracao");
                    }
                    else if (roles.Contains("Secretario"))
                    {
                        return RedirectToAction("Index", "Clinica");
                    }
                    else if (roles.Contains("Medico"))
                    {
                        return RedirectToAction("Index", "Consultas");
                    }
                    else if (roles.Contains("Comum"))
                    {
                        return RedirectToAction("Index", "Usuario");
                    }

                }
                else
                {
                    ModelState.AddModelError("", "Nome de usuário ou senha incorretos!");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(login);
        }

        //
        // GET: /Usuario/Cadastro

        public ActionResult Cadastro()
        {
            return View();
        } 

        //
        // POST: /Usuario/Cadastro

        [HttpPost]
        public ActionResult Cadastro(CadastroModels usuario)
        {
            if (ModelState.IsValid)
            {
                MembershipCreateStatus createStatus;
                Membership.CreateUser(usuario.UserName, usuario.Password, usuario.Email, null, null, false, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(usuario.UserName, "Administrador");
                    TempData["sucesso"] = "Cadastro realizado com sucesso! Em breve sua conta será ativada!";
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            return View(usuario);

        }
        
        //
        // GET: /Usuario/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Usuario/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Usuario/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Usuario/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }


        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Este nome de usuário já existe! Por favor, informe um nome de usuário diferente!";

                case MembershipCreateStatus.DuplicateEmail:
                    return "Este e-mail já está cadastrado no sistema! Por favor, informe um e-mail diferente!";

                case MembershipCreateStatus.InvalidPassword:
                    return "A senha informada é inválida! Por favor, informe uma senha válida!";

                case MembershipCreateStatus.InvalidEmail:
                    return "O e-mail informado é inválido! Por favor, informe um e-mail válido!";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "O nome de usuário informado é inválido! Por favor, informe um nome de usuário válido!";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }

    }
}
